package com.zansc.longd.service.impl.s;

import com.zansc.longd.domain.entity.s.Menu;
import com.zansc.longd.domain.mapper.s.MenuMapper;
import com.zansc.longd.model.base.out.MenuOut;
import com.zansc.longd.service.s.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MenuServiceImpl implements MenuService {
    
    @Autowired
    private MenuMapper menuMapper;
    
    @Override
    public void addMenu(Menu menu) {
        menuMapper.insert(menu);
    }
    
    @Override
    public List<MenuOut> getMenu() {
        Menu menu = new Menu();
        ArrayList<MenuOut> menuTree = new ArrayList<>();
        menu.setParentId(new Long(0));
        List<Menu> menuList = menuMapper.select(menu);
        System.out.println(menuList);
        if (menuList != null) {
            for (Menu menu1 : menuList) {
                List<MenuOut> menuTree1 = new ArrayList<>();
                MenuOut menuOut = new MenuOut();
                menuOut.setId(menu1.getId());
                menuOut.setAuthName(menu1.getMenuname());
                menuOut.setOrder(menu1.getOrders());
                menuOut.setPath(menu1.getUrl());
                menuOut.setIcons(menu1.getIcons());
                Menu menu2 = new Menu();
                menu2.setParentId(menu1.getId());
                List<Menu> select = menuMapper.select(menu2);
                if (select != null) {
                    for (Menu menu3 : select) {
                        MenuOut menuOut1 = new MenuOut();
                        menuOut1.setId(menu3.getId());
                        menuOut1.setAuthName(menu3.getMenuname());
                        menuOut1.setOrder(menu3.getOrders());
                        menuOut1.setPath(menu3.getUrl());
                        menuTree1.add(menuOut1);
                    }
                    Collections.sort(menuTree1,new MyComparator());
                    menuOut.setChildren(menuTree1);
                }
                menuTree.add(menuOut);
            }
        }
        Collections.sort(menuTree,new MyComparator());
        return menuTree;
    }
    
    class MyComparator implements Comparator<MenuOut> {
        
        @Override
        public int compare(MenuOut o1, MenuOut o2) {
            //升序
            return o1.getOrder() - o2.getOrder();
            //降序：后面会具体分析为什么降序
            //return o.a - o1.a;
        }
    }
    
}
